package br.com.puertorico.mecanismos.ui.security;

import java.io.IOException;

import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.view.facelets.FaceletContext;
import javax.faces.view.facelets.FaceletException;
import javax.faces.view.facelets.TagAttribute;
import javax.faces.view.facelets.TagConfig;
import javax.faces.view.facelets.TagHandler;

import br.com.puertorico.common.loggin.Logger;

public class AuthorizationRoleTag extends TagHandler {

	private static final long serialVersionUID = 19L;

	private static final Logger _log = Logger
			.getLogger(AuthorizationRoleTag.class);

	private TagAttribute isUserInRole;

	public AuthorizationRoleTag(TagConfig config) {
		super(config);
		this.isUserInRole = this.getRequiredAttribute("isUserInRole");
	}

	@Override
	public void apply(FaceletContext ctx, UIComponent parent)
			throws IOException, FacesException, FaceletException, ELException {
		try {
			String roleSet = isUserInRole.getValue();
			if (roleSet.contains("#{")) {
				roleSet = (String) isUserInRole.getObject(ctx);
			}
			String[] roleArray = roleSet.contains(",") ? roleSet.split("[,]")
					: new String[] { roleSet };
			for (String role : roleArray) {
				if (ctx.getFacesContext().getExternalContext().isUserInRole(
						role.replaceAll("[\\s]", ""))) {
					this.nextHandler.apply(ctx, parent);
					break;
				}
			}
		} catch (Exception e) {
			_log.info(e);
		}
	}
}